package com.swind.fast.modules.app.railway.report.service.impl;

import com.swind.fast.common.system.base.service.impl.SwindServiceImpl;
import com.swind.fast.modules.app.railway.report.entity.RailwayReportTaskWorkload;
import com.swind.fast.modules.app.railway.report.mapper.RailwayReportTaskWorkloadMapper;
import com.swind.fast.modules.app.railway.report.service.IRailwayReportTaskWorkloadService;
import org.springframework.stereotype.Service;

import com.swind.fast.modules.system.entity.SysUser;
import com.swind.fast.modules.system.service.ISysUserService;
import com.swind.fast.modules.system.entity.SysDepart;
import com.swind.fast.modules.system.service.ISysDepartService;
import com.swind.fast.modules.system.entity.SysUserDepart;
import com.swind.fast.modules.system.service.ISysUserDepartService;

import com.swind.fast.modules.app.railway.project.entity.RailwayProject;
import com.swind.fast.modules.app.railway.project.service.IRailwayProjectService;
import com.swind.fast.modules.app.railway.project.entity.RailwayProjectWorkman;
import com.swind.fast.modules.app.railway.project.service.IRailwayProjectWorkmanService;
import com.swind.fast.modules.app.railway.project.entity.RailwayProjectWorkTask;
import com.swind.fast.modules.app.railway.project.service.IRailwayProjectWorkTaskService;
import com.swind.fast.modules.app.railway.project.entity.RailwayProjectTaskPoint;
import com.swind.fast.modules.app.railway.project.service.IRailwayProjectTaskPointService;

import com.swind.fast.modules.system.service.ISysDictService;
import com.swind.fast.common.system.vo.DictModel;

import org.springframework.beans.factory.annotation.Autowired;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.swind.fast.common.util.oConvertUtils;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 项目
 */

@Slf4j
@Service
public class RailwayReportTaskWorkloadServiceImpl extends SwindServiceImpl<RailwayReportTaskWorkloadMapper, RailwayReportTaskWorkload> implements IRailwayReportTaskWorkloadService {

    @Autowired
    private IRailwayProjectService railwayProjectService;

    @Autowired
    private IRailwayProjectWorkTaskService railwayProjectWorkTaskService;

    @Autowired
    private IRailwayProjectTaskPointService railwayProjectTaskPointService;

    @Autowired
    private IRailwayProjectWorkmanService railwayProjectWorkmanService;

    @Autowired
    private ISysDictService sysDictService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDepartService sysDepartService;

    @Autowired
    private ISysUserDepartService sysUserDepartService;

    public Map<String, Object> getWorkloadPieChart(String projectId) {

        QueryWrapper<RailwayReportTaskWorkload> queryWrapper = new QueryWrapper<RailwayReportTaskWorkload>().eq("project_id", projectId).last("limit 1");
        RailwayReportTaskWorkload workload = this.getOne(queryWrapper);
        if (oConvertUtils.isEmpty(workload)) return null;

        Map<String, Object> result = new HashMap<String, Object>();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> item = new HashMap<String, Object>();
        item.put("name", "已下任务书");
        item.put("value", workload.getAssigned());
        list.add(item);
        item = new HashMap<String, Object>();
        item.put("name", "已完成现场测试");
        item.put("value", workload.getOnsited());
        list.add(item);
        item = new HashMap<String, Object>();
        item.put("name", "外业质量评价合格");
        item.put("value", workload.getQualified());
        list.add(item);
        item = new HashMap<String, Object>();
        item.put("name", "已完成分析");
        item.put("value", workload.getAnalyzed());
        list.add(item);
        item = new HashMap<String, Object>();
        item.put("name", "已完成复核");
        item.put("value", workload.getReviewed());
        list.add(item);
        result.put("data", list);

        return result;
    }

    public Map<String, Object> getWorkloadPieChartV2(String projectId) {

        QueryWrapper<RailwayReportTaskWorkload> queryWrapper = new QueryWrapper<RailwayReportTaskWorkload>().eq("project_id", projectId);

        // QueryWrapper<RailwayReportTaskWorkload> queryWrapper = new QueryWrapper<RailwayReportTaskWorkload>().eq("project_id", projectId).last("limit 1");
        // RailwayReportTaskWorkload workload = this.getOne(queryWrapper);
        // if (oConvertUtils.isEmpty(workload)) return null;

        Map<String, Object> result = new HashMap<String, Object>();
        // List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        // Map<String, Object> item = new HashMap<String, Object>();
        // item.put("name", "已下任务书");
        // item.put("value", workload.getAssigned());
        // list.add(item);
        // item = new HashMap<String, Object>();
        // item.put("name", "已完成现场测试");
        // item.put("value", workload.getOnsited());
        // list.add(item);
        // item = new HashMap<String, Object>();
        // item.put("name", "外业质量评价合格");
        // item.put("value", workload.getQualified());
        // list.add(item);
        // item = new HashMap<String, Object>();
        // item.put("name", "已完成分析");
        // item.put("value", workload.getAnalyzed());
        // list.add(item);
        // item = new HashMap<String, Object>();
        // item.put("name", "已完成复核");
        // item.put("value", workload.getReviewed());
        // list.add(item);
        // result.put("data", list);

        return result;
    }

    public Map<String, Object> getWorkloadChart(String projectId) {
        Map<String, Object> result = new HashMap<String, Object>();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        QueryWrapper<RailwayProjectWorkTask> queryWrapper = new QueryWrapper<RailwayProjectWorkTask>().eq("project_id", projectId);
        Integer taskCount = railwayProjectWorkTaskService.count(queryWrapper);
        Map<String, Object> item = new HashMap<String, Object>();
        item.put("name", "已下任务书");
        item.put("value", taskCount);
        list.add(item);

        QueryWrapper<RailwayProjectTaskPoint> pqueryWrapper = new QueryWrapper<RailwayProjectTaskPoint>().select("status, count(id) as total").eq("project_id", projectId).groupBy("status");
        List<Map<String, Object>> listMap = railwayProjectTaskPointService.listMaps(pqueryWrapper);
        Integer ptotal = 0, qualified = 0, analyzed = 0, reviewd = 0;

        for (Map<String, Object> pitem : listMap) {
            Integer status = oConvertUtils.getInt(pitem.get("status"));
            Integer total = oConvertUtils.getInt(pitem.get("total"));
            ptotal = ptotal + total;
            // log.info("ptotal: {}, total: {}, qualified: {}, analyzed: {}, reviewd: {}", ptotal, total, qualified, analyzed, reviewd);
            // switch (status) {
            //     case >1 :
            //         ptotal = ptotal + total;
            //     case >3 :
            //         qualified = qualified + total;
            //     case >4 :
            //         analyzed = analyzed + total;
            //     case >7 :
            //         reviewd = reviewd + total;
            //     default:
            //         break;
            // }

            switch (status) {
                case 4 :
                    qualified = qualified + total;
                    break;
                case 5 :
                    qualified = qualified + total;
                    analyzed = analyzed + total;
                    break;
                case 6 :
                    qualified = qualified + total;
                    analyzed = analyzed + total;
                    break;
                case 7 :
                    qualified = qualified + total;
                    analyzed = analyzed + total;
                    break;
                case 8 :
                    qualified = qualified + total;
                    analyzed = analyzed + total;
                    reviewd = reviewd + total;
                    break;
                default:
                    break;
            }
        }

        item = new HashMap<String, Object>();
        item.put("name", "已完成现场测试");
        item.put("value", ptotal);
        list.add(item);
        item = new HashMap<String, Object>();
        item.put("name", "外业质量评价合格");
        item.put("value", qualified);
        list.add(item);
        item = new HashMap<String, Object>();
        item.put("name", "已完成分析");
        item.put("value", analyzed);
        list.add(item);
        item = new HashMap<String, Object>();
        item.put("name", "已完成复核");
        item.put("value", reviewd);
        list.add(item);

        result.put("data", list);
        return result;
    }

    public Map<String, Object> getWorkloadDetail(String projectId) {
        Map<String, Object> result = new HashMap<String, Object>();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        QueryWrapper<RailwayProject> queryWrapper = new QueryWrapper<RailwayProject>().select("name").eq("id", projectId).last("limit 1");
        RailwayProject project = railwayProjectService.getOne(queryWrapper);
        if (oConvertUtils.isEmpty(project)) {

            result.put("projectName", "暂无记录");
            result.put("onsiteCount", 0);
            result.put("qulifiedCount", 0);
            result.put("analyzedCount", 0);
            result.put("reviewedCount", 0);
            // result.put("data", list);
            return result;
        }
        result.put("projectName", project.getName());

        QueryWrapper<RailwayProjectWorkTask> tqueryWrapper = new QueryWrapper<RailwayProjectWorkTask>().eq("project_id", projectId);
        Integer taskCount = railwayProjectWorkTaskService.count(tqueryWrapper);
        result.put("taskCount", taskCount);

        QueryWrapper<RailwayProjectTaskPoint> pqueryWrapper = new QueryWrapper<RailwayProjectTaskPoint>().select("status, count(id) as total").eq("project_id", projectId).groupBy("status");
        List<Map<String, Object>> listMap = railwayProjectTaskPointService.listMaps(pqueryWrapper);
        Integer ptotal = 0, qualified = 0, analyzed = 0, reviewd = 0;

        for (Map<String, Object> pitem : listMap) {
            Integer status = oConvertUtils.getInt(pitem.get("status"));
            Integer total = oConvertUtils.getInt(pitem.get("total"));
            ptotal = ptotal + total;

            switch (status) {
                case 4 :
                    qualified = qualified + total;
                    break;
                case 5 :
                    qualified = qualified + total;
                    analyzed = analyzed + total;
                    break;
                case 6 :
                    qualified = qualified + total;
                    analyzed = analyzed + total;
                    break;
                case 7 :
                    qualified = qualified + total;
                    analyzed = analyzed + total;
                    break;
                case 8 :
                    qualified = qualified + total;
                    analyzed = analyzed + total;
                    reviewd = reviewd + total;
                    break;
                default:
                    break;
            }
        }

        result.put("onsiteCount", ptotal);
        result.put("qulifiedCount", qualified);
        result.put("analyzedCount", analyzed);
        result.put("reviewedCount", reviewd);
        return result;
    }

    public List<Map<String, Object>> getDepartmentSummary(String startDate, String endDate) {

        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

        // 部门下项目ID
        List<RailwayProject> listProject = railwayProjectService.getProjectByOrgCode(startDate, endDate);
        if (listProject.size() < 1) {
            return result;
        }

        List<String> projectIds = listProject.stream().map(RailwayProject::getId).collect(Collectors.toList());
        log.info("projectIds: {}", projectIds);

        // 计划工作量


        // 已下任务书
        QueryWrapper<RailwayProjectWorkTask> tqueryWrapper = new QueryWrapper<RailwayProjectWorkTask>().select("count(id) as total, test_method_dict as method, sum(hole_plan) as depth").in("project_id", projectIds).ne("test_method_dict", "").groupBy("test_method_dict");
        List<Map<String, Object>> tlistMap = railwayProjectWorkTaskService.listMaps(tqueryWrapper);
        log.info("tlistMap: {}", tlistMap);
        // result.put("tlistMap", tlistMap);

        // 现场测试完成
        QueryWrapper<RailwayProjectTaskPoint> pqueryWrapper = new QueryWrapper<RailwayProjectTaskPoint>().select("count(id) as total, test_method_dict as method, sum(deep) as depth").in("project_id", projectIds).ne("test_method_dict", "").groupBy("test_method_dict");
        List<Map<String, Object>> plistMap = railwayProjectTaskPointService.listMaps(pqueryWrapper);
        log.info("plistMap: {}", plistMap);

        // 已完成分析
        QueryWrapper<RailwayProjectTaskPoint> aqueryWrapper = new QueryWrapper<RailwayProjectTaskPoint>().select("count(id) as total, test_method_dict as method, sum(deep) as depth").in("project_id", projectIds).ne("test_method_dict", "").gt("status", "4").groupBy("test_method_dict");
        List<Map<String, Object>> alistMap = railwayProjectTaskPointService.listMaps(aqueryWrapper);
        log.info("alistMap: {}", alistMap);

        List<DictModel> listDict = sysDictService.queryDictItemsByCode("railway_project_test_method");

        Map<String, Object> item;
        for (DictModel dict : listDict) {
            item = new HashMap<String, Object>();
            String dictValue = dict.getValue();
            String dictText = dict.getText();
            item.put("method", dictText);

            Optional<Map<String, Object>> taskOpt = tlistMap.stream().filter(p -> p.get("method").toString().equals(dictValue)).findFirst();
            if (taskOpt.isPresent()) {
                Map<String, Object> opt = taskOpt.get();
                String total = opt.get("total").toString();
                log.info("total: {}, dictValue: {}", total, dictText);
                item.put("taskCount", opt.get("total") + "/" + opt.get("depth"));
            } else {
                item.put("taskCount", "0/0");
            }

            Optional<Map<String, Object>> pointOpt = plistMap.stream().filter(p -> p.get("method").toString().equals(dictValue)).findFirst();
            if (pointOpt.isPresent()) {
                Map<String, Object> opt = pointOpt.get();
                String total = opt.get("total").toString();
                log.info("total: {}, dictValue: {}", total, dictText);
                item.put("pointCount", opt.get("total") + "/" + opt.get("depth"));
            } else {
                item.put("pointCount", "0/0");
            }

            Optional<Map<String, Object>> aOpt = alistMap.stream().filter(p -> p.get("method").toString().equals(dictValue)).findFirst();
            if (aOpt.isPresent()) {
                Map<String, Object> opt = aOpt.get();
                String total = opt.get("total").toString();
                log.info("total: {}, dictValue: {}", total, dictText);
                item.put("analyzeCount", opt.get("total") + "/" + opt.get("depth"));
            } else {
                item.put("analyzeCount", "0/0");
            }

            result.add(item);
        }

        log.info("result: {}", result);
        return result;
    }

    public Map<String, Object> getBigScreenProjectCount(String orgCode) {
        Map<String, Object> result = new HashMap<String, Object>();
        // 项目数量
        QueryWrapper<RailwayProject> queryWrapper = new QueryWrapper<RailwayProject>().select("id", "category", "status").eq("org_code", orgCode);
        List<RailwayProject> listProject = railwayProjectService.list(queryWrapper);

        Long lfinished = listProject.stream().filter(p -> p.getStatus() == 5).count();
        Integer finished = oConvertUtils.getInt(lfinished);
        Integer infinished = listProject.size() - finished;

        result.put("finished", finished);
        result.put("infinished", infinished);

        List<DictModel> listDict = sysDictService.queryDictItemsByCode("railway_project_category");

        Map<String, Object> category = new HashMap<String, Object>();
        for (DictModel dict : listDict) {
            String dictValue = dict.getValue();
            String dictText = dict.getText();

            Long categoryCount = listProject.stream().filter(p -> p.getCategory().toString().equals(dictValue)).count();
            category.put(dictText, categoryCount);
        }

        // log.info("category: {}", category);
        result.put("category", category);

        return result;
    }

    public Map<String, Object> getBigScreenPersonCount(String orgCode) {
        Map<String, Object> result = new HashMap<String, Object>();

        QueryWrapper<SysDepart> dqueryWrapper = new QueryWrapper<SysDepart>().eq("org_code", orgCode).last("limit 1");
        SysDepart depart = sysDepartService.getOne(dqueryWrapper);
        String departId = depart.getId();

        QueryWrapper<SysUserDepart> duqueryWrapper = new QueryWrapper<SysUserDepart>().eq("dep_id", departId);
        List<SysUserDepart> listDepartUser = sysUserDepartService.list(duqueryWrapper);
        List<String> userIds = listDepartUser.stream().map(SysUserDepart::getUserId).collect(Collectors.toList());

        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>().select("count(id) as total", "user_category").in("id", userIds).ne("user_category", "").groupBy("user_category");
        List<Map<String, Object>> listMap = sysUserService.listMaps(queryWrapper);

        List<DictModel> listDict = sysDictService.queryDictItemsByCode("railway_user_category");
        Map<String, Object> dpersonCategory = new HashMap<String, Object>();
        for (DictModel dict : listDict) {
            String dictValue = dict.getValue();
            String dictText = dict.getText();

            Optional<Map<String, Object>> categoryCount = listMap.stream().filter(p -> String.valueOf(p.get("user_category")).equals(dictValue)).findFirst();

            if (categoryCount.isPresent()) {
                Map<String, Object> opt = categoryCount.get();
                String total = opt.get("total").toString();
                // log.info("total: {}, dictValue: {}", total, dictText);
                dpersonCategory.put(dictText, total);
            } else {
                dpersonCategory.put(dictText, "0");
            }
        }

        result.put("dpersonCategory", dpersonCategory);

        // 项目人员统计
        QueryWrapper<RailwayProject> ppqueryWrapper = new QueryWrapper<RailwayProject>().select("id", "category", "status").eq("org_code", orgCode);
        List<RailwayProject> listProject = railwayProjectService.list(ppqueryWrapper);
        List<String> projectIds = listProject.stream().map(RailwayProject::getId).collect(Collectors.toList());

        QueryWrapper<RailwayProjectWorkman> pwqueryWrapper = new QueryWrapper<RailwayProjectWorkman>().select("count(id) total", "position").in("project_id", projectIds).groupBy("position");
        List<Map<String, Object>> pwCategory = railwayProjectWorkmanService.listMaps(pwqueryWrapper);
        List<DictModel> plistDict = sysDictService.queryDictItemsByCode("railway_project_position");
        Map<String, Object> ppersonCategory = new HashMap<String, Object>();
        for (DictModel dict : plistDict) {
            String dictValue = dict.getValue();
            String dictText = dict.getText();

            Optional<Map<String, Object>> categoryCount = pwCategory.stream().filter(p -> String.valueOf(p.get("position")).equals(dictValue)).findFirst();

            if (categoryCount.isPresent()) {
                Map<String, Object> opt = categoryCount.get();
                String total = opt.get("total").toString();
                // log.info("total: {}, dictValue: {}", total, dictText);
                ppersonCategory.put(dictText, total);
            } else {
                ppersonCategory.put(dictText, "0");
            }
        }
        result.put("ppersonCategory", ppersonCategory);

        return result;
    }

    public List<Map<String, String>> getBigScreenProjectPointCount(String orgCode) {

        QueryWrapper<RailwayProject> queryWrapper = new QueryWrapper<RailwayProject>().select("id", "name").eq("org_code", orgCode);
        List<RailwayProject> listProject = railwayProjectService.list(queryWrapper);
        List<String> projectIds = listProject.stream().map(RailwayProject::getId).collect(Collectors.toList());

        QueryWrapper<RailwayProjectTaskPoint> pqueryWrapper = new QueryWrapper<RailwayProjectTaskPoint>().select("count(id) as total, project_id as projectId").in("project_id", projectIds).groupBy("project_id");
        List<Map<String, Object>> plistMap = railwayProjectTaskPointService.listMaps(pqueryWrapper);
        // log.info("plistMap: {}", plistMap);

        List<Map<String, String>> ppresult = new ArrayList<Map<String, String>>();
        plistMap.stream().forEach(item -> {
            Map<String, String> pmap = new HashMap<String, String>();
            String projectId = String.valueOf(item.get("projectId"));
            String projectTotal = String.valueOf(item.get("total"));
            Optional<RailwayProject> project = listProject.stream().filter(p -> p.getId().equals(projectId)).findFirst();
            if (project.isPresent()) {
                RailwayProject opt = project.get();
                String projectName = opt.getName();
                pmap.put("name", projectName);
                pmap.put("total", projectTotal);
                ppresult.add(pmap);
            }
        });

        return ppresult;

    }

    public List<Map<String, String>> getBigScreenProjectPointMonthSummary(String orgCode) {

        QueryWrapper<RailwayProject> queryWrapper = new QueryWrapper<RailwayProject>().select("id", "name").eq("org_code", orgCode);
        List<RailwayProject> listProject = railwayProjectService.list(queryWrapper);
        List<String> projectIds = listProject.stream().map(RailwayProject::getId).collect(Collectors.toList());

        QueryWrapper<RailwayProjectTaskPoint> pqueryWrapper = new QueryWrapper<RailwayProjectTaskPoint>().select("count(id) as total, project_id as projectId").in("project_id", projectIds).groupBy("project_id");
        List<Map<String, Object>> plistMap = railwayProjectTaskPointService.listMaps(pqueryWrapper);
        // log.info("plistMap: {}", plistMap);

        List<Map<String, String>> ppresult = new ArrayList<Map<String, String>>();
        plistMap.stream().forEach(item -> {
            Map<String, String> pmap = new HashMap<String, String>();
            String projectId = String.valueOf(item.get("projectId"));
            String projectTotal = String.valueOf(item.get("total"));
            Optional<RailwayProject> project = listProject.stream().filter(p -> p.getId().equals(projectId)).findFirst();
            if (project.isPresent()) {
                RailwayProject opt = project.get();
                String projectName = opt.getName();
                pmap.put("name", projectName);
                pmap.put("total", projectTotal);
                ppresult.add(pmap);
            }
        });

        return ppresult;

    }
}
